package com.lpy.trans.controller;


import com.lpy.trans.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

//    注入对象
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private UserService userService;

//    插入用户信息
    @RequestMapping("/register")
    public String register(String userName, String passWord) {

        // 获取事务
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);


        Integer result = userService.insertUser(userName, passWord);

        log.info("数据插入: " + result);

        // 回滚事务
        //dataSourceTransactionManager.rollback(transaction);

        // 提交事务
        dataSourceTransactionManager.commit(transaction);

        return "注册成功";
    }
}
